from io import BytesIO

import requests
import json
import pymysql
import re
from PIL import Image
import pdb

token = ""

"""
以login身份登录
@:return 将token变量置换为新的token
"""


def loginAdmin():
    global token
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.63'
    }
    data = {
        'identity': 'admin',
        'desStr': 'EwSSctvjsSy3mRlLK88JvfucUEKQGCfP',
        'captcha': '',
        'sessionId': ''
    }
    response = requests.post('http://localhost:8088/admin/login', headers=headers, data=data)
    result = response.json()
    token = result['data']['JEECMS-Auth-Token']


# 上传内容
def upload_content(title, quotation, content, channelId, shortTitle, releaseTime, author):
    global token
    headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.63',
        'JEECMS-Auth-Token': token
    }
    data = {
        'json': {
            'realTitle': title,
            'quotation': quotation,
            'mobile': '',
            'content': content
        },
        'modelName': '新闻',
        'modelId': 912,
        'channelId': channelId,
        'title': {
            'titleColor': '#666666',
            'titleIsBold': 'true',
            'title': title
        },
        'shortTitle': shortTitle,
        'releaseTime': releaseTime,
        'contentTag': '',
        'contentSourceId': {
            'sourceLink': '',
            'sourceName': ''
        },
        'author': author,
        'description': '',
        'resource': '',
        'releaseTerrace': [
            'releasePc',
            'releaseWap',
            'releaseApp',
            'releaseMiniprogram'
        ],
        'tplPc': '',
        'tplMobile': '',
        'allowComment': 1,
        'viewControl': 1,
        'type': 5,
    }
    response = requests.post('http://localhost:8088/admin/content', headers=headers, data=json.dumps(data))
    result = response.json()
    print(result)


"""
上传文件与图片
@:param 文件与图片绝对路径
@:return 服务器存储图片路径
"""


def upload_img(imgFileName):
    global token
    headers = {
        # 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarynyD6j1lKJPdXBvKN',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.63',
        'JEECMS-Auth-Token': token
    }
    data = {
        'typeStr': '',
        'addToRes': 'false',
        'mark': 'false',
        'spaceId': ''
    }
    files = {'uploadFile': (open(imgFileName, 'rb'))}
    response = requests.post('http://localhost:8088/admin/upload/o_upload', headers=headers, files=files, data=data)
    result = response.json()
    return result['data']['fileUrl']


"""
替换content中的src
@:param content 内容
"""


def sub_content(content):
    # 初始化匹配src和href，href为文件，src为图片
    srcUrl = re.compile("(href|src|SRC)=(\"|\')(.*?)(\"|\')")
    # 通过正则匹配content中所有src和href
    srcItems = srcUrl.findall(content)
    if srcItems:
        for srcItem in srcItems:
            # 判断是否为远程资源，远程资源无需处理
            if re.search("http://", srcItem[2]):
                print(str(item['id']) + "have src but on Internet")
            else:
                # 此处拿到每个图片的连接并且不是远程的需要替换
                print(srcItem[2])
                print(str(item['id']) + "need sub src here")
                # 此处为替换src，srcItem[2]为旧数据中的路径 例如 /js/kindeditor/attached/file/20190113/20190113041255_95328.xls，机场
                # 给的数据，路径为驼峰写法，要注意新建路径，
                # upload_img 传入文件的绝对路径即可上传并且返回服务器的文件保存路径
                content = re.sub(srcItem[2], upload_img('D:/gongxiang' + srcItem[2]), content)
    else:
        # 内容中无图片
        print("only text")
    print(content)
    return content


"""
使用前把上面的localhost:8088改成对应端口
"""
if __name__ == '__main__':
    # 使用admin登录获取token
    loginAdmin()
    # 连接线上数据库
    conn = pymysql.connect(
        host='59.111.94.192',
        port=3721,
        user='yfb_test', password='BH_yfb_test1024',
        database='btjc_old',
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 这里写sql查出一个导入数据的列表，根据现在有的数据，大概是19-20年，
    sql = "select * from product_infos where id = 61544"
    cursor.execute(sql)
    resAll = cursor.fetchall()
    # 遍历每条数据
    for item in resAll:
        print(item)
        # 获取旧数据内容
        content = item['content']
        # 将文件和图片路径替换
        content = sub_content(content)
        # 上传
        upload_content(item['title'], item['ft_title'], content, 2063, item['ft_title'], str(item['create_time']),
                       item['create_name'])
